#include <assert.h>
#include <string.h>

#include "node_to_iris_module.h"
#include "uarch/mreq.h"

//extern Simulator Sim;

/********************
 * Bus_network Interface
 ********************/
Node_iris_module::Node_iris_module (ModuleID moduleID)
    : Module(moduleID, "FI_")
{
}

Node_iris_module::~Node_iris_module ()
{
}

void Node_iris_module::tick ()
{
    Mreq *request = NULL;
    
    bool is_buffer_empty = false;
    node_terminal->send_buffer_id = -1;
    for ( uint i=0; i<node_terminal->ni_buffer_width ; i++ )
        if ( node_terminal->ni_buffers[i] )
        {
            is_buffer_empty = true;
            node_terminal->send_buffer_id = i;
            break;
        }

    while (is_buffer_empty && (request = read_input_port ()) != NULL)
    {
//        request->print_msg(moduleID," Node_iris_module send to node_terminal");
        node_terminal->handle_issue_pkt_event(request);

        is_buffer_empty = false;
        node_terminal->send_buffer_id = -1;
        for ( uint i=0; i<node_terminal->ni_buffer_width ; i++ )
            if ( node_terminal->ni_buffers[i] )
            {
                is_buffer_empty = true;
                node_terminal->send_buffer_id = i;
                break;
            }
    }
}

void Node_iris_module::tock ()
{
    Mreq *request;
    while (!in_request_queue.empty()) 
    {
        request = in_request_queue.front ();
        in_request_queue.pop ();

        assert (request->dest_mid.nodeID == moduleID.nodeID && "wrong destination?");
        //request->add_history(request, "fakenet");
        write_output_port (request, Global_Clock + 10);
    }
}
